package me.illtamer.infinite.util;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import me.illtamer.infinite.pojo.Response;
import me.illtamer.infinite.pojo.TransObject;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

@Slf4j
public class JsonUtil {

    /**
     * 将接收的 json 封装为对象
     * @param response {@link TransObject}
     * @apiNote 后续考虑替换jackson?
     * success {
     *      from: ''
     *      to: ''
     *      trans_result: [
     *          {sec: '', dst: ''},
     *      ]
     * }
     * error {
     *     error_code: ''
     *     error_msg: ''
     * }
     */
    @NotNull
    public static TransObject getObject(String response) {
        JsonObject object = new Gson().fromJson(response, JsonObject.class);

        JsonElement error = object.get("error_code");
        if (error != null) {
            log.warn("Error translate response (Auto skipped): {}", response);
            return new TransObject(null, null, null, Response.get(error.getAsInt()));
        }

        String from = object.get("from").getAsString();
        String to = object.get("to").getAsString();
        JsonArray trans_result = object.getAsJsonArray("trans_result");
        List<TransObject.TransPair> transPairs = new ArrayList<>(trans_result.size());
        for (JsonElement element : trans_result) {
            JsonObject temp = element.getAsJsonObject();
            transPairs.add(new TransObject.TransPair(temp.get("src").getAsString(), temp.get("dst").getAsString()));
        }
        return new TransObject(from, to, transPairs, Response.SUCCESS);
    }

}
